"""
系统设置模块
功能：模型参数配置、用户权限管理、系统参数设置
支持：模型更新、系统维护
"""

import json
import os
from typing import Dict, Any

class ConfigManager:
    def __init__(self, config_file: str = 'system_config.json'):
        self.config_file = config_file
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """
        加载配置文件
        :return: 配置字典
        """
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"配置文件加载失败: {e}")
                return self._get_default_config()
        else:
            return self._get_default_config()
    
    def _get_default_config(self) -> Dict[str, Any]:
        """
        获取默认配置
        :return: 默认配置字典
        """
        return {
            'system': {
                'name': '道路交通事件智能分类与优先级管理系统',
                'version': '1.0.0',
                'debug': False
            },
            'model': {
                'svm': {
                    'kernel': 'rbf',
                    'C': 1.0,
                    'gamma': 'scale'
                },
                'decision_tree': {
                    'max_depth': 10,
                    'min_samples_split': 2
                }
            },
            'database': {
                'host': 'localhost',
                'port': 3306,
                'username': 'admin',
                'password': 'password',
                'database': 'event_classifier'
            },
            'permissions': {
                'admin': ['read', 'write', 'delete', 'config'],
                'user': ['read'],
                'guest': []
            }
        }
    
    def get_config(self, section: str = None) -> Dict[str, Any]:
        """
        获取配置
        :param section: 配置节名称，如果为None则返回所有配置
        :return: 配置字典
        """
        if section:
            return self.config.get(section, {})
        return self.config
    
    def update_config(self, section: str, key: str, value: Any) -> bool:
        """
        更新配置
        :param section: 配置节名称
        :param key: 配置键
        :param value: 配置值
        :return: 是否更新成功
        """
        try:
            if section not in self.config:
                self.config[section] = {}
            
            self.config[section][key] = value
            return True
        except Exception as e:
            print(f"配置更新失败: {e}")
            return False
    
    def save_config(self) -> bool:
        """
        保存配置到文件
        :return: 是否保存成功
        """
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"配置保存失败: {e}")
            return False
    
    def get_model_params(self, model_name: str) -> Dict[str, Any]:
        """
        获取模型参数
        :param model_name: 模型名称
        :return: 模型参数字典
        """
        return self.config.get('model', {}).get(model_name, {})
    
    def update_model_params(self, model_name: str, params: Dict[str, Any]) -> bool:
        """
        更新模型参数
        :param model_name: 模型名称
        :param params: 模型参数字典
        :return: 是否更新成功
        """
        try:
            if 'model' not in self.config:
                self.config['model'] = {}
            
            self.config['model'][model_name] = params
            return True
        except Exception as e:
            print(f"模型参数更新失败: {e}")
            return False
    
    def check_permission(self, role: str, action: str) -> bool:
        """
        检查用户权限
        :param role: 用户角色
        :param action: 操作
        :return: 是否有权限
        """
        permissions = self.config.get('permissions', {})
        role_permissions = permissions.get(role, [])
        return action in role_permissions

# 使用示例
def main():
    config_manager = ConfigManager()
    
    # 获取系统配置
    system_config = config_manager.get_config('system')
    print("系统配置:")
    for key, value in system_config.items():
        print(f"  {key}: {value}")
    
    # 获取模型参数
    svm_params = config_manager.get_model_params('svm')
    print("\nSVM模型参数:")
    for key, value in svm_params.items():
        print(f"  {key}: {value}")
    
    # 更新模型参数
    new_svm_params = {
        'kernel': 'linear',
        'C': 2.0,
        'gamma': 'auto'
    }
    if config_manager.update_model_params('svm', new_svm_params):
        print("\nSVM模型参数更新成功")
    
    # 检查权限
    print("\n权限检查:")
    print(f"  管理员是否有写权限: {config_manager.check_permission('admin', 'write')}")
    print(f"  普通用户是否有删除权限: {config_manager.check_permission('user', 'delete')}")
    print(f"  访客是否有读权限: {config_manager.check_permission('guest', 'read')}")
    
    # 保存配置
    # if config_manager.save_config():
    #     print("\n配置保存成功")

if __name__ == "__main__":
    main()